var mailRegExp = "[^<]*<?[^@]+@([^>\\s]+)>?";
var associationsDomainFolder = [];

function TDCStructure() {
	this.folder = null;
	this.mails = createMutableArray();
	this.nbMails = 0;
}

function getDomainFromAddress(mailAddress) {
	var domain = "null";
	var resultats = mailAddress.toLowerCase().match(mailRegExp);
	if(resultats != null) {
		domain = resultats[1];
	}
	if (traceEnabled) {
		log("The address [" + mailAddress + "] will be converted to domain [" + domain + "]");
	}
	return domain;
}

function browseFolders(tdcStructArray, folder) {
	var subfolders = folder.subFolders;
	while(subfolders.hasMoreElements()) {
		var subfolder = subfolders.getNext();
		var name = subfolder.prettiestName;
		if (tdcStructArray[name] != null) {
			tdcStructArray[name].folder = subfolder;	
		}
	}
}

function inList(domain, list) {
	if ((list == null) || (list.length == 0)) {
		return false;
	}
	for(var e in list) {
		if (e == domain) {
			return true;
		}
	}
	return false;
}

function getAssociatedFolderName(domain) {
	if ((associationsDomainFolder == null) || (associationsDomainFolder.length == 0)) {
		return domain;
	}
	for(var e in associationsDomainFolder) {
		if (e == domain) {
			return associationsDomainFolder[e];
		}
	}
	return domain;
}

function browseMails(tdcStructArray, folder, ignoreList) {
	var messages = folder.messages;
	while(messages.hasMoreElements()) {
		var message = messages.getNext();
		var messageHeader = getHeader(message);
		var domain = getDomainFromAddress(messageHeader.author);
		if(!inList(domain, ignoreList)) {
			domain = getAssociatedFolderName(domain);
			if (tdcStructArray[domain] == null) {
				tdcStructArray[domain] = new TDCStructure();
			}
			tdcStructArray[domain].mails.appendElement(message, false);
			tdcStructArray[domain].nbMails = tdcStructArray[domain].nbMails + 1;
		}
	}
}

function createFolders(tdcStructArray, folder, neededMessageCount) {
	for(var domain in tdcStructArray) {
		if ((tdcStructArray[domain].folder == null) && (tdcStructArray[domain].nbMails >= neededMessageCount)) {
			var subfolder = folder.addSubfolder(domain);
			tdcStructArray[domain].folder = subfolder;
		}
	}
}

function moveMails(tdcStructArray, folder) {
	for(var domain in tdcStructArray) {
		if ((tdcStructArray[domain].folder != null) && (tdcStructArray[domain].mails != null) && (tdcStructArray[domain].nbMails > 0)) {
			if (traceEnabled) {
				log("Moving " + tdcStructArray[domain].nbMails + " mails to [" + tdcStructArray[domain].folder.prettiestName + "]");
			}
			moveMessages(folder, tdcStructArray[domain].mails, tdcStructArray[domain].folder);
		}
	}
}